<?php
session_start();
require_once("dbconnection.php");

//Gets User information from the DB returns it as an array.
function userInfo($user)
{
    $name = mysql_real_escape_string($user);
    $line = "SELECT * FROM Users WHERE email =\"" .$name ."\"";
    $command = mysql_query($line);
    if(!$command)
    {
        echo 'Could not run query: ' . mysql_error();
        exit;
    }

    $array = mysql_fetch_row($command);

    return $array;


}


//Sets Sessions variables of the user.
function setSession($user)
{

    $row = userInfo($user);


    $_SESSION['User'] = $row[0];
    $_SESSION['ID'] = $row[1];
    $_SESSION['First'] = $row[2];
    $_SESSION['Last'] = $row[3];
    $_SESSION['Office'] = $row[4];
    $_SESSION['Phone'] = $row[5];
    $_SESSION['Author'] = $row[7];
    $_SESSION['Publisher'] = $row[8];
    $_SESSION['Admin'] = $row[9];
    $_SESSION['Approve'] = $row[10];


}

function enterUser($Email,$First,$Last,$Office,$Phone,$Password)
{

    $bool = false;
    $Author = true;
    $data = "INSERT INTO Users (Email, First, Last, Office, Phone, Password, Author)
VALUES('$Email','$First','$Last','$Office','$Phone','$Password', '$Author')";

    if(mysql_query($data))
    {
        $bool = true;
    }
    else
    {
        $bool = false;
    }

    return $bool;

}

function checkUser($Email)
{
    $sql_check = mysql_query("select id from Users where Email='".$Email ."'") or die(mysql_error());

    return $sql_check;
}

/*
 * getAssetInfo($assetID)
 *     Gets the file info for a given asset if it exists, or NULL if it doesn't
 *     exist. Expects the asset's ID as the function argument.
 *
 *     Returns: an array of asset info with the following values:
 *         ['ID']           Unique Asset ID
 *         ['Filename']     System Filename
 *         ['Name']         Original Filename
 *         ['Title']        Asset Title
 *         ['Description']  Asset Description
 *         ['Path']         Asset Virtual Path
 *         ['Media']        Media Type
 *         ['AddedDate']    Date Uploaded
 *         ['AddedUser']    User Who Uploaded Asset
 */
function getAssetInfo($assetID) {
    $queryString =  sprintf("SELECT * FROM Assets WHERE ID = %s",
        mysql_real_escape_string($assetID));

    $result = mysql_query($queryString);

    // Return NULL if DB error or asset does not exist in DB
    if ($result === FALSE || mysql_num_rows($result) == 0) {
        return NULL;
    }

    // Return associative array of the query results
    $row = mysql_fetch_assoc($result);

    // Free the resources associated with the result set
    mysql_free_result($result);

    return $row;

}


/*
 * getPageInfo($pageAlias)
 *     Gets the file info for a given content page if it exists, or NULL if it
 *     doesn't exist. Expects the page's URL alias as the function argument.
 *
 *     Returns: an array of page info with the following values:
 *         ['Filename']     System Filename
 *         ['ID']           Unique Page ID
 *         ['Author']       Author's User Name
 *         ['Title']        Page Title
 *         ['Date']         Creation Date
 *         ['AuthDate']     Approved Date
 *         ['Approve']      Approved Flag
 *         ['Publisher']    Publisher name
 *         ['LastDate']     Revision Date
 *         ['LastUser']     Revision User Name
 *         ['LastFilename'] Revision Filename
 *         ['LastTitle']    Revision Page Title
 *         ['LastDesc']     Revision Page Description
 *         ['Alias']        Virtual Filename
 *         ['Desc']         Page Description
 */
function getPageInfo($pageAlias) {
    $queryString = sprintf("SELECT * FROM Content WHERE Alias = '%s'",
        mysql_real_escape_string($pageAlias));

    $result = mysql_query($queryString);

    // Return NULL if DB error or page does not exist in DB
    if ($result === FALSE || mysql_num_rows($result) == 0) {
        return NULL;
    }

    // Return associative array of the query results
    $row = mysql_fetch_assoc($result);

    // Free the resources associated with the result set
    mysql_free_result($result);

    return $row;
}


/*
 * Function returns an array of all users in database
 * If $approveFlag = 0, look up the unapproved users
 * If $approveFlag = 1.
 */
function adminDash($approveFlag)
{
    $query = mysql_query("SELECT ID, Email, First, Last, Author, Publisher, Admin FROM Users WHERE Approve = $approveFlag");
    while($output = mysql_fetch_array($query))
    $array[] = $output;

    mysql_free_result($query);
    return $array;
}

/*
 * Function approves user who's id is $id and sets permissions
 */
function approveUser($id, $adminFlag, $pubFlag, $authorFlag)
{
    mysql_query("UPDATE Users SET Approve = '1', Admin='$adminFlag', Author='$authorFlag', Publisher='$pubFlag' WHERE ID = '$id'");
}

/*
 * Function denies user $id by deleting them from the database
 */
function denyUser($id)
{
    mysql_query("DELETE FROM Users WHERE ID = '$id'");
}

/*
 * Function approves page $page for publishing and says who published it
 */
function publishPage($page, $publisher)
{
   $date = date("Y-m-d H:i:s");
   mysql_query("UPDATE Content SET Approve = '1', Publisher = '$publisher', AuthDate = '$date' WHERE ID = '$page'");
}

/*
 * Function un-publishes page $pageid
 */
function unpublishPage($pageid)
{
  mysql_query("UPDATE Content SET Approve = '0' WHERE ID = '$pageid'");
}

/*
 * Function returns an array of all pages waiting to be approved for $username
 */
function authorDash($username)
{
    $query = mysql_query("SELECT * FROM Content WHERE Approve = 0 AND (LastUser = '$username' OR Author = '$username')");

    while($output = mysql_fetch_array($query))
    $array[] = $output;

    mysql_free_result($query);
    return $array;
}

/*
 * addNewContent($alias, $title, $creator, $content, $fileRoot)
 *     Creates a new content page with the given parameters:
 *         $alias       The virtual filename
 *         $title       The page title
 *         $creator     The user who created the content
 *         $content     The page contents
 *         $desc        A description of the page
 *         $fileRoot    The content file root
 *
 *     Returns: TRUE on success, FALSE otherwise
 */
function addNewContent($alias, $title, $author, $content, $desc, $fileRoot) {

    $filename = generateFilename($alias, $fileRoot);
    $date = date("Y-m-d H:i:s");
    $title = stripcslashes($title);
    $desc = stripcslashes($desc);
    
    $queryString = sprintf("INSERT INTO Content (`Filename`, `Author`, `Title`,".
        " `Date`, `Alias`, `Desc`) VALUES ('%s', '%s', '%s', '%s', '%s', '%s')",
        mysql_real_escape_string($filename),
        mysql_real_escape_string($author),
        mysql_real_escape_string($title),
        mysql_real_escape_string($date),
        mysql_real_escape_string($alias),
        mysql_real_escape_string($desc));

    $result = mysql_query($queryString);

    if ($result === TRUE) {
        $fp = fopen($fileRoot . $filename, "wb");
        $fileContent = stripcslashes($content);
        fwrite($fp, $fileContent);
        fclose($fp);
        chmod($fileRoot . $filename, 0744);
    }

    return $result;

}

/*
 * 
 */
function editContent($alias, $newTitle, $newAuthor, $newContent, $newDesc, $fileRoot) {

	$pageInfo = getPageInfo($alias);

    $newFilename = generateFilename($alias, $fileRoot);
    $newDate = date("Y-m-d H:i:s");
    $newTitle = stripcslashes($newTitle);
    $newDesc = stripcslashes($newDesc);

    $queryString = sprintf("UPDATE Content SET `LastDate`='%s', `LastUser`='%s',".
        " `LastFilename`='%s', `LastTitle`='%s', `LastDesc`='%s' WHERE".
        " `ID` = %s",
        mysql_real_escape_string($newDate),
        mysql_real_escape_string($newAuthor),
        mysql_real_escape_string($newFilename),
        mysql_real_escape_string($newTitle),
        mysql_real_escape_string($newDesc),
        $pageInfo['ID']);

    $result = mysql_query($queryString);

    if ($result === TRUE) {
        $fp = fopen($fileRoot . $newFilename, "wb");
        $fileContent = stripcslashes($newContent);
        fwrite($fp, $fileContent);
        fclose($fp);
        chmod($fileRoot . $newFilename, 0644);
    }

    return $result;

}

/*
 * 	approveContent()
 *		Approves a page.
 *		If approve flag is 0, this function changes it to 1.
 *		If approve flag is 1, this funciton copies revision data such as LastFilename and LastUser
 *		to its original data and empties the revision data.
 */
function approveContent($alias, $publisher, $fileRoot) {

    $pageInfo = getPageInfo($alias);

    if ($pageInfo !== NULL) {

        $pubDate = date("Y-m-d H:i:s");

        if ($pageInfo['Approve'] == 0) {
            // If page is not a revision, just update Approve flag
            $queryString = sprintf("UPDATE Content SET `AuthDate`='%s', `Approve`=1,".
                " `Publisher`='%s' WHERE `ID` = %s",
                mysql_real_escape_string($pubDate),
                mysql_real_escape_string($publisher),
                $pageInfo['ID']);

            $result = mysql_query($queryString);

            return $result;

        } else if (!empty($pageInfo['LastFilename'])) {

            $oldFilename = $pageInfo['Filename'];
            $newFilename = $pageInfo['LastFilename'];
            $newAuthor = $pageInfo['LastUser'];
            $newTitle = $pageInfo['LastTitle'];
            $newDate = $pageInfo['LastDate'];
            $newDesc = $pageInfo['LastDesc'];


            // If page is a revision, copy values from all Last... fields
            $queryString = sprintf("UPDATE Content SET `Filename`='%s',".
                " `Author`='%s',".
                " `Title`='%s',".
                " `Date`='%s',".
                " `AuthDate`='%s',".
                " `Approve`=1,".
                " `Publisher`='%s',".
                " `LastDate`='',".
                " `LastUser`='',".
                " `LastFilename`='',".
                " `LastTitle`='',".
                " `LastDesc`='',".
                " `Desc`='%s'".
                " WHERE `ID`=%s",
                mysql_real_escape_string($newFilename),
                mysql_real_escape_string($newAuthor),
                mysql_real_escape_string($newTitle),
                mysql_real_escape_string($newDate),
                mysql_real_escape_string($pubDate),
                mysql_real_escape_string($publisher),
                mysql_real_escape_string($newDesc),
                $pageInfo['ID']);

            $result = mysql_query($queryString);

            // Delete old file
            unlink ($fileRoot . $oldFilename);

            return $result;

        }

        return $true;

    }
}

/*
 * generateFilename($pagealias)
 *     Generates a unique filename for the specified page alias
 *
 *     Returns: the unique filename string
 *
 */
function generateFilename($pagealias, $root) {

    $newfilename = str_replace("/", "_", $pagealias);

    if (file_exists($root . $newfilename)) {
        $appendNum = 0;
        while (file_exists($root . $newfilename . $appendNum)) {
            $appendNum++;
        }
    }

    return $newfilename . $appendNum;
}

/*
 * getAllAssetsByPath()
 *     Gets all assets from the database, and sorts them by Path.
 *     e.g. $assets['Stuff'] points to an array of assets whose Path property is
 *     'Stuff'
 *
 *     Returns: an array of assets on success, NULL otherwise
 */

function getAllAssetsByPath() {

    $queryString = "SELECT * FROM Assets ORDER BY Path, Title";
    $result = mysql_query($queryString);

    // Place all assets in 2-dim array, keyed on path
    while($row = mysql_fetch_array($result)) {
        $assets[$row['Path']][] = $row;
    }

    return $assets;

}

/*
 *	getPublisherInfo()
 *		Gets following data for publisher's page to list all pages.
 *		Data: ID, Author, Title, Date, Approve, LastDate, LastUser, Alias
 *
 *		Returns: array of the data above
 */
function getPublisherInfo() {
    $queryStr = mysql_query("SELECT * FROM Content");

    while($row = mysql_fetch_array($queryStr)) {
        $result[] = $row;
    }
    mysql_free_result($queryStr);
    return $result;
}


function getAllPublishedPages()
{
    $queryStr = mysql_query("SELECT * FROM Content WHERE Approve = 1");

    while($row = mysql_fetch_array($queryStr)) {
        $result[] = $row;
    }
    mysql_free_result($queryStr);
    return $result;
}



function deleteAsset($assetId){
    $result = mysql_query("DELETE FROM Assets WHERE ID=".$assetId);

    return $result;
}


/*
 *	deleteContent()
 *		Deletes a page from Content table.
 *		If argument $flag is 0, the page is deleted.
 *		If argument $flag is 1, revision of the page is deleted and
 *		the original page remains.
 */
function deleteContent($alias, $flag)
{
    $pageInfo = getPageInfo($alias);

		if ($flag == 0) {
			$Filename = $pageInfo['Filename'];
			$queryStr = "DELETE FROM Content WHERE ID=".$pageInfo['ID'];
		} else {
			$Filename = $pageInfo['LastFilename'];
			$queryStr = "UPDATE Content SET `LastDate`='', `LastUser`='', `LastFilename`='',".
        	        	" `LastTitle`='', `LastDesc`=''".
        	        	" WHERE ID=".$pageInfo['ID'];
		}

	$result = mysql_query($queryStr);
	
    unlink ($fileRoot . $Filename);
}

?>
